
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Rest;
import com.cmc.dao.RestDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class RestDaoHibernate extends BaseDaoHibernate implements RestDao {

    /**
     * @see com.cmc.dao.RestDao#getRests(com.cmc.model.Rest)
     */
    public List getRests(final Rest rest) {
        //return getHibernateTemplate().find("from Rest");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (rest == null) {
            return getHibernateTemplate().find("from Rest");
        } else {
            // filter on properties set in the rest
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(rest).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Rest.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.RestDao#getRest(Long id)
     */
    public Rest getRest(final Long id) {
        Rest rest = (Rest) getHibernateTemplate().get(Rest.class, id);
        if (rest == null) {
            log.warn("uh oh, rest with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Rest.class, id);
        }

        return rest;
    }

    /**
     * @see com.cmc.dao.RestDao#saveRest(Rest rest)
     */    
    public void saveRest(final Rest rest) {
        getHibernateTemplate().saveOrUpdate(rest);
    }

    /**
     * @see com.cmc.dao.RestDao#removeRest(Long id)
     */
    public void removeRest(final Long id) {
        getHibernateTemplate().delete(getRest(id));
    }
}
